package com.lz.sports.vm.group

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.lz.library.base.BaseModel
import com.lz.library.base.BaseViewModel
import com.lz.sports.bean.DeviceGroup
import com.lz.sports.bean.DeviceInfo
import com.lz.sports.core.ProjectManager
import com.lz.sports.db.DeviceDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext

// 设备分组
class DeviceGroupListViewModel : BaseViewModel<BaseModel>() {

    //项目ID
    val projectId = ProjectManager.examProjectId()

    val projectName = ProjectManager.examProjectName()

    //设备组列表
    val deviceGroupList = MutableLiveData<List<DeviceGroup>>()

    //辅助设备列表
    val assistDeviceInfoList = MutableLiveData<List<DeviceInfo>>()

    //添加的设备组
    val addDeviceGroup = MutableLiveData<DeviceGroup>()

    override fun onCreate(owner: LifecycleOwner) {
        launch {
            flow { emit(DeviceDatabase.get().findDeviceGroupListWithInfo(projectId)) }
                .flowOn(Dispatchers.Default)
                .collect { deviceGroupList.value = it }
        }

        launch {
            flow { emit(DeviceDatabase.get().findAssistDeviceInfoList(projectId)) }
                .flowOn(Dispatchers.Default)
                .collect { assistDeviceInfoList.value = it }
        }
    }

    override fun onResume(owner: LifecycleOwner) {
        deviceGroupList.value?.forEach {
            it.resetBattery()
        }
    }

    fun addDeviceGroup(name: String) {
        launch {
            val async = async(Dispatchers.Default) {
                DeviceGroup(projectId, name).apply { id = DeviceDatabase.get().addDeviceGroup(this) }
            }
            addDeviceGroup.value = async.await()
        }
    }

    //删除组
    fun delete(groupId: Int) {
        launch {
            withContext(Dispatchers.Default) {
                DeviceDatabase.get().deleteDeviceGroup(groupId)
            }
        }
    }

}